export const formatTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}
export const DeviceManager = {
  /**
   * 获取设备唯一标识
   */
  async getDeviceId() {
    try {
      // 1. 尝试从缓存获取
      let deviceId = wx.getStorageSync('device_id');
      if (deviceId) {
        return deviceId;
      }

      // 2. 生成新的设备ID
      const systemInfo = await this.getSystemInfo();
      deviceId = await this.generateUniqueId(systemInfo);
      
      // 3. 缓存设备ID
      wx.setStorageSync('device_id', deviceId);
      return deviceId;
    } catch (error) {
      console.error('获取设备ID失败:', error);
    }
  },

  /**
   * 获取系统信息
   */
  getSystemInfo() {
    return new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success: resolve,
        fail: reject
      });
    });
  },

  /**
   * 生成唯一设备ID
   */
  async generateUniqueId(systemInfo) {
    const {
      model,           // 设备型号
      system,          // 操作系统版本
      platform,        // 客户端平台
      pixelRatio,      // 设备像素比
      screenWidth,     // 屏幕宽度
      screenHeight,    // 屏幕高度
      windowWidth,     // 可使用窗口宽度
      windowHeight,    // 可使用窗口高度
      language,        // 微信设置的语言
      brand           // 设备品牌
    } = systemInfo;
console.log(encodeURIComponent(systemInfo))
    // 组合多个设备特征
    const deviceFeatures = [
      model || 'unknown',
      system || 'unknown',
      platform || 'unknown',
      brand || 'unknown',
      `${screenWidth}x${screenHeight}`,
      `${windowWidth}x${windowHeight}`,
      pixelRatio?.toString() || '1',
      language || 'zh_CN'
    ].join('|');
    // 使用简单hash算法
    return encodeURIComponent(deviceFeatures);
  },
};